/*******************************************************************************
 * Package: com.hngtrust.iir.notice.controller
 * Type:    NoticeController
 * Date:    2021/3/22 9:23
 *
 * Copyright (c) 2021 HUANENG GUICHENG TRUST CORP.,LTD All Rights Reserved.
 *
 * You may not use this file except in compliance with the License.
 *******************************************************************************/
package com.hngtrust.iir.notice.controller;

import com.hngtrust.clickhouse.notice.entity.AppNotice;
import com.hngtrust.clickhouse.notice.entity.AppNoticeSentiment;
import com.hngtrust.clickhouse.notice.service.AppNoticeSentimentService;
import com.hngtrust.clickhouse.notice.service.AppNoticeService;
import com.hngtrust.framework.bind.ResponseInfo;
import com.hngtrust.framework.page.PageResult;
import com.hngtrust.framework.page.service.PageService;
import com.hngtrust.framework.security.util.SecurityUtils;
import com.hngtrust.iir.base.service.NoticeTypeService;
import com.hngtrust.iir.constant.Constant;
import com.hngtrust.iir.dto.ReqDTO;
import com.hngtrust.clickhouse.notice.dto.ListNoticeReqDTO;
import com.hngtrust.iir.notice.controller.dto.DownNoticeReqVO;
import com.hngtrust.iir.notice.controller.dto.ListNoticeRespVO;
import com.hngtrust.iir.notice.controller.dto.QueryByCompIdReqVO;
import com.hngtrust.iir.notice.controller.dto.QueryByNoticeIdReqVO;
import com.hngtrust.iir.user.entity.SelfTag;
import com.hngtrust.iir.user.entity.TagRel;
import com.hngtrust.iir.user.entity.User;
import com.hngtrust.iir.user.service.SelfTagService;
import com.hngtrust.iir.user.service.TagRelService;
import com.hngtrust.iir.util.FileUtils;
import com.hngtrust.iir.util.HtmlUtils;
import com.tiger.web.annotation.DownloadMapping;
import com.tiger.web.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 新闻公告
 *
 * @author Keqiwei
 * @date 2021/3/22 9:23
 */
@Slf4j
@Api(tags = "新闻公告")
@RestController
@RequestMapping("/notice")
public class NoticeController {
    @Autowired
    private AppNoticeService appNoticeService;
    @Autowired
    private PageService pageService;
    @Autowired
    private TagRelService tagRelService;
    @Autowired
    private SelfTagService selfTagService;
    @Value("${tiger.minio.out.address}")
    private String minioAddress;
    @Autowired
    private NoticeTypeService noticeTypeService;
    
    @Autowired
    @Qualifier(value = "minIoFileService")
    private FileService fileService;
    
    // 本地文件服务
    @Autowired
    @Qualifier("localFileService")
    private FileService localFileService;
    
    @Autowired
    private AppNoticeSentimentService appNoticeSentimentService;
    @ApiOperation("获取公告列表")
    @PostMapping("/list-notice")
    public ResponseInfo<PageResult<ListNoticeRespVO>> listNotice(@ApiParam(value = "请求列表") @Valid @RequestBody ReqDTO<ListNoticeReqDTO> dto){
        PageResult<AppNotice> page = pageService
                .page(dto.getPageParam(), () -> appNoticeService.queryListNotice(dto.getContent()));
        List<AppNotice> rows = page.getRows();
        List<ListNoticeRespVO> notices = new ArrayList<>();
        for (AppNotice appNotice :rows){
            ListNoticeRespVO respDTO = new ListNoticeRespVO();
            BeanUtils.copyProperties(appNotice,respDTO);
            List<SelfTag> list = new ArrayList<>();
            TagRel tagRel = new TagRel();
            tagRel.setDataType(dto.getContent().getDataType());
            tagRel.setDataId(appNotice.getId());
            List<TagRel> tagRels = tagRelService.queryList(tagRel);
            if (appNotice.getHtml() != null && !appNotice.getHtml().isEmpty()){
                respDTO.setHtml(HtmlUtils.replaceHtmlTag(appNotice.getHtml(),minioAddress));
            }
            if (appNotice.getFilePath() != null && !appNotice.getFilePath().isEmpty()){
                respDTO.setFilePath(HtmlUtils.filePathAppend(appNotice.getFilePath(),minioAddress));
            }
            if (null != appNotice.getType() && !appNotice.getType().isEmpty()){
                String[] split = appNotice.getType().split(",");
                List<String> types = new ArrayList<>();
                for (String s : split) {
                    types.add(noticeTypeService.queryById(Long.parseLong(s)).getName());
                }
                respDTO.setType(types);
            }
            respDTO.setLabels(tagRels);
            notices.add(respDTO);
        }
        PageResult<ListNoticeRespVO> pageResult = new PageResult<>();
        pageResult.setRows(notices);
        pageResult.setPage(page.getPage());
        return new ResponseInfo<PageResult<ListNoticeRespVO>>(pageResult);
    }
    
    /**
     * 根据公司id获取公告
     */
    @ApiOperation("根据公司id获取公告")
    @PostMapping("/query-compId")
    public ResponseInfo<PageResult<ListNoticeRespVO>> queryByCompId(@ApiParam(value = "公司id") @Valid @RequestBody ReqDTO<QueryByCompIdReqVO> dto){
        
        PageResult<AppNotice> page = pageService.page(dto.getPageParam(), () -> appNoticeService.queryByComp(dto.getContent().getCompId()));
        List<AppNotice> rows = page.getRows();
        List<ListNoticeRespVO> notices = new ArrayList<>();
        for (AppNotice appNotice : rows) {
            ListNoticeRespVO respDTO = new ListNoticeRespVO();
            BeanUtils.copyProperties(appNotice, respDTO);
            if (appNotice.getHtml() != null && !appNotice.getHtml().isEmpty()){
                respDTO.setHtml(HtmlUtils.replaceHtmlTag(appNotice.getHtml(),minioAddress));
            }
            
            if (appNotice.getFilePath() != null && !appNotice.getFilePath().isEmpty()){
                respDTO.setFilePath(HtmlUtils.filePathAppend(appNotice.getFilePath(),minioAddress));
            }
            TagRel tagRel = new TagRel();
            tagRel.setDataType(Constant.TAG_DATATYPE_NOTICE);
            tagRel.setDataId(appNotice.getId());
            List<TagRel> tagRels = tagRelService.queryList(tagRel);
            
            respDTO.setLabels(tagRels);
            AppNoticeSentiment sentiment = new AppNoticeSentiment();
            sentiment.setNoticeId(appNotice.getId());
            List<String> compIds = appNoticeSentimentService.queryList(sentiment).stream()
                    .map(AppNoticeSentiment::getCompId).collect(Collectors.toList());
            List<String> compNames = appNoticeSentimentService.queryList(sentiment).stream()
                    .map(AppNoticeSentiment::getEntity).collect(Collectors.toList());
            respDTO.setCompIds(compIds);
            if (compNames != null && compNames.size()>10){
                int i = compNames.indexOf(dto.getContent().getCompName());
                if (i<=9){
                    compNames = compNames.subList(0,10);
                }else {
                    compNames=  compNames.subList(i-9,i+1);
                }
                
            }
            respDTO.setCompNames(compNames);
            if (null != appNotice.getType() && !appNotice.getType().isEmpty()){
                String[] split = appNotice.getType().split(",");
                List<String> types = new ArrayList<>();
                for (String s : split) {
                    types.add(noticeTypeService.queryById(Long.parseLong(s)).getName());
                }
                respDTO.setType(types);
            }
            
            notices.add(respDTO);
        }
        PageResult<ListNoticeRespVO> pageResult = new PageResult<>();
        pageResult.setRows(notices);
        pageResult.setPage(page.getPage());
        return new ResponseInfo<PageResult<ListNoticeRespVO>>(pageResult);
    }
    
    @ApiOperation("根据id查询")
    @PostMapping("/query-id")
    public ResponseInfo<ListNoticeRespVO> queryById(@ApiParam(value = "公告id") @Valid @RequestBody QueryByNoticeIdReqVO vo) {
        AppNotice appNotice = appNoticeService.queryById(vo.getId());
        ListNoticeRespVO respDTO = new ListNoticeRespVO();
        BeanUtils.copyProperties(appNotice, respDTO);
        if (appNotice.getHtml() != null && !appNotice.getHtml().isEmpty()){
            respDTO.setHtml(HtmlUtils.replaceHtmlTag(appNotice.getHtml(),minioAddress));
        }
        if (appNotice.getFilePath() != null && !appNotice.getFilePath().isEmpty()){
            respDTO.setFilePath(HtmlUtils.filePathAppend(appNotice.getFilePath(),minioAddress));
        }
        TagRel tagRel = new TagRel();
        tagRel.setDataType(Constant.TAG_DATATYPE_NOTICE);
        tagRel.setDataId(appNotice.getId());
        List<TagRel> tagRels = tagRelService.queryList(tagRel);
    
        if (null != appNotice.getType() && !appNotice.getType().isEmpty()){
            String[] split = appNotice.getType().split(",");
            List<String> types = new ArrayList<>();
            for (String s : split) {
                types.add(noticeTypeService.queryById(Long.parseLong(s)).getName());
            }
            respDTO.setType(types);
        }
        respDTO.setLabels(tagRels);
        AppNoticeSentiment sentiment = new AppNoticeSentiment();
        sentiment.setNoticeId(appNotice.getId());
        List<String> compIds = appNoticeSentimentService.queryList(sentiment).stream()
                .map(a -> a.getCompId()).collect(Collectors.toList());
        List<String> compNames = appNoticeSentimentService.queryList(sentiment).stream()
                .map(a -> a.getEntity()).collect(Collectors.toList());
        respDTO.setCompIds(compIds);
        respDTO.setCompNames(compNames);
        return new ResponseInfo<>(respDTO);
    }
   
    @ApiOperation("下载公告")
    @DownloadMapping("/down-notice")
    public void downNotice(DownNoticeReqVO vo, HttpServletResponse response) throws IOException {
        String filePath = appNoticeService.queryById(vo.getId()).getFilePath();
    
        User loginUser = (User) SecurityUtils.getLoginUser().getAdditionalInfo();

        String fileName = filePath.substring(filePath.lastIndexOf('/') + 1);
        if(fileName.isEmpty()){
            fileName = filePath;
        }
        String ext = fileName.substring(fileName.lastIndexOf('.'));
    
        String directory = System.getProperty("java.io.tmpdir");
        File file = new File(directory,fileName);
        fileService.download(filePath,file);
    
        File file2 = File.createTempFile(UUID.randomUUID().toString(),ext);
        String waterMark = loginUser.getUserCode() + " " + loginUser.getName();
        File downFile = file2;
        if(ext.toLowerCase().equals(".pdf")){
            FileUtils.waterMarkPdf(file.getPath(),file2.getPath(),waterMark);
        }
        //        else if(ext.toLowerCase().equals(".doc")){
        //            //todo word
        //            FileUtils.waterMarkPdf(file.getPath(),file2.getPath(),waterMark);
        //        }
        else{
            downFile = file;
        }
    
        localFileService.download(downFile.getPath(), response);
        try {
            if(!file.delete()){
                log.error("删除本地临时文件错误：{}" , directory+"/"+fileName);
            }
            if(!file2.delete()){
                log.error("删除本地临时文件错误" );
            }
        }
        catch (Exception e) {
            log.error("删除本地临时文件错误：{}" , directory+"/"+fileName);
        }

    }
    
}
